<?php
require(APPPATH.'libraries/REST_Controller.php');

class Transaction extends REST_Controller {
	function send_post()
	{
		$file_name = '';
		$branch_id = $this->post('branch_id');
		$profit = $this->post('transaction_profit');
		$error = array();
		if ($branch_id == null){
			array_push($error,'branch_id is required');

		}
		if(!is_int(intval($branch_id))){
			array_push($error,'invalid branch_id');

		}
		if ($profit == null){
			array_push($error,'profit is required');

		}
		if(!is_numeric($profit) || $profit < 0){
			array_push($error,'invalid transaction_profit');
			
		}
		if (sizeof($error) > 0){
			$this->response($error, 400);
		}

		if (isset($_FILES['userfile']) && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
			$file_name = $branch_id .'_'. now().'.csv';
			$config['upload_path'] = './uploads/transactions/';
			$config['allowed_types'] = '*';
			$config['max_size']	= '20000';
			$config['file_name']= $file_name;
			$this->upload->initialize($config);
			if (!$this->upload->do_upload())
			{
				$error = array('file_error' => $this->upload->display_errors());
				file_put_contents ('5.txt', $this->upload->display_errors() . $this->upload->file_type);
				$this->response($error, 400);
			}
		}else{
			$this->response('"userfile" is required', 400);
		}
		$this->load->model('transaction_model');
		if ($submit_id=$this->transaction_model->add($branch_id,$file_name,$profit)){

// 			$exec = exec('/opt/php/bin/php -f /usr/local/apache/htdocs/CG3002/application/bg_process/bg.php '.$file_name.' '.$submit_id.' '.$branch_id.' 2>&1', $output, $result);
// 			echo var_dump($exec);
// 			echo '<br>';
// 			echo var_dump($output);
// 			echo '<br>';
// 			echo var_dump($result);
// 			echo '<br>';
			
// 			$source = fopen('/usr/local/apache/htdocs/CG3002/uploads/transactions/' . $file_name, 'r');
// 			while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
// 			{
// 				//$this->transaction_model->add_detail($submit_id, $data[0],$branch_id,$data[1],$data[3],$data[4],$data[5],$data[6]);
// 			}
// 			fclose($source);
			exec('nohup /opt/php/bin/php -f /usr/local/apache/htdocs/CG3002/application/bg_process/bg.php '.$file_name.' '.$submit_id.' '.$branch_id.' > /dev/null 2>&1 &');
			$this->response("transaction upload", 201);
		}else
			$this->response("invalid request", 404);
	}
}